#!/usr/bin/env python
# encoding: utf-8
"""
@author:zwb
@file: articles.py
@contact: zwb15083976291@163.com
@time: 2022/02/22
"""
from django.db.models import Q

from common.models import BlogArticle
from common.serializers.serializer import FrontEndArticleSerializer, ArticlerecommendSerializer
from utils.responses import CommonResponse, CommonAPIResponseStatus
from utils.views import BaseGenericAPIView


# 返回文章详情
class ArticlesDetailsView(BaseGenericAPIView):
    serializer_class = FrontEndArticleSerializer
    diff_methods_request_params = dict(get=dict(required=['id']))

    def get(self, request):
        ret, message = self.validate_request_params()
        if not ret:
            return CommonResponse(CommonAPIResponseStatus.BAD_REQUEST, message=message)
        blog = BlogArticle.objects.filter(id=self.query_data.get("id")).first()
        blog.reading_quantity += 1
        blog.save()
        return CommonResponse(
            data=self.serializer_class(instance=blog).data)


class ArticlesRecommendView(BaseGenericAPIView):
    serializer_class = ArticlerecommendSerializer
    diff_methods_request_params = dict(get=dict(required=['id']))

    def get(self, request):
        ret, message = self.validate_request_params()
        if not ret:
            return CommonResponse(CommonAPIResponseStatus.BAD_REQUEST, message=message)
        serial_fields = ['id', 'articles_title', 'articles_image_url', 'create_time']
        current = BlogArticle.objects.filter(id=self.query_data.get('id')).first()
        updown = self.updown_data(current.id, serial_fields)
        newests = ArticlerecommendSerializer(
            instance=BlogArticle.objects.filter(articles_status=0).filter(~Q(id=current.id)).order_by(
                '-create_time').all()[:5], many=True,
            serial_fields=serial_fields).data
        recommends = ArticlerecommendSerializer(
            instance=BlogArticle.objects.filter(articles_status=0).filter(
                Q(categorie=current.categorie) & ~Q(id=current.id)).order_by(
                '-create_time')[:3],
            many=True, serial_fields=serial_fields).data
        return CommonResponse(data=dict(updown=updown, newests=newests, recommends=recommends))

    def updown_data(self, current_id, serial_fields):
        # 查询当前id的前一个和后一篇文章
        result = dict(
            next_data=dict(existe=False, data=None),
            pre_data=dict(existe=False, data=None),
        )
        data = dict(
            pre_data=BlogArticle.objects.filter(articles_status=0).filter(id__lt=current_id).order_by('-id').first(),
            next_data=BlogArticle.objects.filter(articles_status=0).filter(id__gt=current_id).order_by('id').first()
        )
        for key, item in data.items():
            if item:
                result[key]['existe'] = True
                result[key]['data'] = ArticlerecommendSerializer(instance=item, serial_fields=serial_fields).data

        return result
